import re

from django import forms
from django.core.exceptions import ValidationError

from vote.models import User
from vote.utils import to_md5_hex


class LoginForm(forms.Form):
    username = forms.CharField(min_length=4, max_length=20)
    password = forms.CharField(min_length=8, max_length=20)
    captcha = forms.CharField(min_length=4, max_length=4)

    def clean_username(self):
        username = self.cleaned_data['username']
        pattern = re.compile(r'\w{4,20}')
        if not pattern.fullmatch(username):
            raise ValidationError('用户名由字母、数字、下划线构成且长度为4-20个字符')
        return username

    def clean_password(self):
        password = self.cleaned_data['password']
        return to_md5_hex(password)


class RegisterForm(forms.ModelForm):
    repassword = forms.CharField(min_length=8, max_length=20)
    mobilecode = forms.CharField(min_length=6, max_length=6)

    def clean_username(self):
        username = self.cleaned_data['username']
        pattern = re.compile(r'\w{4,20}')
        if not pattern.fullmatch(username):
            raise ValidationError('用户名由字母、数字、下划线构成且长度为4-20个字符')
        return username

    def clean_password(self):
        password = self.cleaned_data['password']
        return to_md5_hex(password)

    def clean_repassword(self):
        password = self.cleaned_data['password']
        repassword = self.cleaned_data['repassword']
        if password != to_md5_hex(repassword):
            raise ValidationError('密码和确认密码需要保持一致')
        return repassword

    class Meta:
        model = User
        exclude = ('no', 'regdate')
